<script setup lang="ts">
import { ref, onMounted,  reactive, nextTick, getCurrentInstance, watch, type Ref, inject } from "vue";
import { useRouter, useRoute, type LocationQueryValue } from "vue-router";
import bus from "../tools/bus";
import * as VideoApi from "../http/videoLabel";
import { Message } from "@arco-design/web-vue";
import { usePageType } from "../tools/usePageType";
import {useFilmReadRight, useVideo} from '@/store';
import type * as VideoType from '../type';
import Dialog from "@/components/dialog/index.vue";

const validateSingleSmallSign: any = inject('validateSingleSmallSign')
const { isView, isCreate, isEdit } = usePageType();
const FilmReadRight = useFilmReadRight();
const router = useRouter();
const route = useRoute();
const videoStore = useVideo();
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
	taskInfo: {
		type: Object,
		default: {}
	},
	formRef: {
		type: Object,
		default: {}
	},
	currnetSeriesResultInfo: {
    type: Object,
    default: {}
  },
  getData: {
    type: Function,
		default: () => {}
  },
	sarIdList: {
    type: Array<string>,
    default: []
  },
	taskId: {
		type: Number,
		default: 0
	},
	nidusList: {
		type: Array<VideoType.NidusItem>,
		default: <VideoType.NidusItem[]>[]
	},
	currentSeriesUid: {
    type: [Number, String],
    default: "",
  },
	validateSmallSignError: {
		type: Function,
		default: () => {}
	},
	validateBigSignError: {
		type: Function,
		default: () => {}
	},
	seriesInfo: {
		type: Array
	},
  visible: {
    type: Boolean,
    default: false
  },
  isReject: {
    type: Boolean,
    default: false
  },
  seriesGroupList: {
    type: Array,
    default: []
  },
  groupIndex: {
    type: Number,
    default: 0
  },
  projectInfo: {
    type: Object,
    default: {}
  }
});
const emits = defineEmits(['update:visible', 'update:groupIndex'])
const { proxy }:any = getCurrentInstance();
interface CallBackData {
	done(closed: boolean): void | boolean | Promise<void | boolean>;
	flag: boolean;
	status: string;
}

function submit() {
  bus.emit("Header.submit");
  emits('update:visible', true);
}

const sectionVisible = ref(false);

const handleCancel = () => {
  emits('update:visible', false);
};

const backPath = ref("");
onMounted(()=>{
  const _backPath = route.query.backPath;
  backPath.value = (_backPath || "") as string;
})

function goback(){
  if( backPath.value === '1' ){
    window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
  } else {
    router.back();
  }
}
const minSignFlag = ref(false);
// 校验阴阳性
/*鉴影阴阳性逻辑：
1、小征像必填项校验与是否勾选阴阳性无关，即小征像什么情况下都需要校验必填项
2、不勾选阴阳性，所有序列大征像必填都要校验
3、勾选阳性：
   阳性序列的大征像不需要校验，阴性序列大征像待校验
4、勾选阴性：
   阴性序列的大征像不需要校验，阳性序列大征像待校验
5、勾选阳性和阴性：
   阴性、阳性序列的大征像都不需要校验*/
const validateYay = async (obj: {status: string, flag: boolean}) => {
	if (props.taskInfo.isYayAttributes) {
		if (props.taskInfo.yayAttributes === 2) {
			// 全不选要校验
			// 校验大小征象
			validateSigns(obj);
		} else {
			if (props.currnetSeriesResultInfo.yayAttributes === null) {
				// 校验阴阳性
				Message.error('请选择阴阳性！');
        emits('update:visible', obj.flag);
			} else {
				if ((props.currnetSeriesResultInfo.yayAttributes === 1 && props.taskInfo.yayAttributes === 3) || (props.currnetSeriesResultInfo.yayAttributes === 2 && props.taskInfo.yayAttributes === 1)) {
					// 只校验小征象
					// const currentSeries = props.nidusList.filter(item => item.id === props.currentSeriesUid);
					const flag = validateMinSign(obj, props.nidusList);
					flag && submitInterface(obj);
				} else {
					validateSigns(obj);
				}
			}
		}
	} else {
		// 全不选要校验
		// 校验大小征象
		const flag = validateMinSign(obj, props.nidusList, true);
		flag && submitInterface(obj);
	}
}
// 校验大征象表单
const validateSigns = async (obj: {status: string, flag: boolean}) => {
	// 校验当前序列的小征象
	const flag = validateMinSign(obj, props.nidusList, true);
	flag && submitInterface(obj);
}

// 校验小征象及其它序列大小征象
const validateMinSign = (obj: {status: string, flag: boolean}, dataList: VideoType.NidusItem[], type: boolean = false) => {
	let flag = true;
	dataList && dataList.forEach((cur, n) => {
		if( !flag ) return;
		if (type) {
			// 大征象层
			cur.seriesForm && cur.seriesForm.forEach(item => {
				if( !flag ) return;
				if (item.required && (item.value === '' || item.value?.length === 0)) {
					// 聚焦错误
          emits('update:visible', obj.flag);
					Message.error({
						content: `序列号为${cur.id}的序列征象的${item.label}不可为空！`,
						closable: true,
						duration: 3000,
					});
					const fileds = <{[x: string]: any}>{};
					fileds[item.field] = {
						status: 'error',
						message: `${item.label}不可为空！`
					}
					flag = false;
					props.validateBigSignError(n, ()=>{
						props.formRef.seriesForm.setFields({
							[item.field]: {...fileds[item.field]}
						});
					});
				}
			})
		}
		cur.child && cur.child.forEach((item, index) => {
			if( !flag ) return;
			item.child && item.child.forEach((it, inde) => {
				if( !flag ) return;
				it.imageAnnoForm && it.imageAnnoForm.forEach((t, i) => {
					if( !flag ) return;
					if (t.required && (t.value === '' || t.value?.length === 0)) {
						// 聚焦错误
            emits('update:visible', obj.flag);
						Message.error({
							content: `序列号为${cur.id}的标注征象的${t.label}不可为空！`,
							closable: true,
							duration: 3000,
						});
						// props.selectItem(n, index, inde);
						const fileds = <{[x: string]: any}>{};
						fileds[t.field] = {
							status: 'error',
							message: `${t.label}不可为空！`
						}
						flag = false;
						props.validateSmallSignError(n, index, inde, ()=> {
							props.formRef.seriesMinSetForm.setFields({
								[t.field]: {...fileds[t.field]}
							});
						});
					}
				});
			})
		})
	})
  if(!flag){
    return flag
  }
  flag = validateAllSeriesSingleSign(obj)
	return flag;
}
// 效验所有序列的单帧标注的小征象
const validateAllSeriesSingleSign = (obj: {status: string, flag: boolean}) => {
  let flag = true
  videoStore.singleAnnoList.forEach((item: any, index: number) => {
    if( !flag ) return;
    item.list && item.list.forEach((it: any, idx: number) => {
      if( !flag ) return;
      it.imageAnnoForm && it.imageAnnoForm.forEach((t: any, i: number) => {
        if( !flag ) return;
        if (t.required && (t.value === '' || t.value?.length === 0)) {
          // 聚焦错误
          emits('update:visible', obj.flag);
          Message.error({
            content: `序列号为${item.id}的标注征象的${t.label}不可为空！`,
            closable: true,
            duration: 3000,
          });
          const fileds = <{[x: string]: any}>{};
          fileds[t.field] = {
            status: 'error',
            message: `${t.label}不可为空！`
          }
          flag = false;
          // 聚焦错误征象，错误单帧列表，错误层数
          validateSingleSmallSign(it.id, ()=>{
            //高亮必填项
            props.formRef.seriesMinSetForm.setFields({
              [t.field]: {...fileds[t.field]}
            })
          })
        }
      });
    })
  })
  return flag
}
const userId = ref<string>('0');
const taskId = ref<string>('0');
const surPlusResult = ref();
const seriesResult = ref();
// 校验完成调用提交接口
const submitInterface = async (obj: {status: string, flag: boolean}) => {
	const sarIdList = props.sarIdList.join(',');
	const result = await VideoApi.submit(sarIdList);
  emits('update:visible', obj.flag);
	if (obj.status === 'save') {
		window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
	} else {
    //编辑并且点击提交并获取新序列的按钮，直接关闭
    if (route.query.type === 'edit') {
      router.back()
    } else {
      getSeries()
    }
	}
}
//提交时效验追踪算法：有帧段就要效验是否追踪过，视频没有标注帧段，不校验；
const validateTrace = (obj: {status: string, flag: boolean}) => {
  // console.log('nidusList',props.nidusList)
  let invalidateItem:any = null
  let invalidateIndex:number = -1
  for(let [index,item] of props.nidusList.entries()){
    const { child } = item
    let find:boolean = false
    for(let itm of child){//帧段
      const { algProcessed } = itm
      if(!algProcessed){
        invalidateItem = item
        invalidateIndex = index
        find = true
        break
      }
    }
    if(find){
      break
    }
  }
  if(invalidateItem){
    //聚焦错误
    emits('update:visible', obj.flag);
    Message.error({
      content: `序列号为${invalidateItem.id}的序列未追踪算法！`,
      closable: true,
      duration: 10000,
    });
    props.validateBigSignError(invalidateIndex, ()=>{});
    return false//不通过
  }else{
    return true//效验通过
  }
}
// 查询是否新切片
const getSeries = async () => {
  userId.value = route.query.userId as string;
  taskId.value = route.query.taskId as string;
  const params = {
    userId: +userId.value,
    taskId: +taskId.value
  }
  seriesResult.value = await VideoApi.userSeriesGet(params);
  // surPlusResult.value = await VideoApi.getSurPlusSeries(+userId.value);
  // const currentResult = surPlusResult.value.filter((item: { id: number; }) => item.id === +taskId.value);
  if (!seriesResult.value) {
    sectionVisible.value = true;
  } else {
    router.go(0);
  }
}
// 提交并切换新序列及提交并关闭
const handleSubmitVisible = async (obj: {status: string, flag: boolean}) => {
  //先效验是否全部跑过追踪算法,后端没有提供标志，通过是否有追踪结节判断
  if (!props.isReject) {//是否废片
    if(props.projectInfo?.needTrace){
      if(!validateTrace(obj)) return
    }
    validateYay(obj);
  }
  if (props.isReject && obj.status === 'save') {
    window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
  }
  if (props.isReject && obj.status === 'more') {
    if (route.query.type === 'edit') {
      emits('update:visible', obj.flag);
      router.back()
    } else {
      getSeries()
    }
  }
}
// 无新切片点击事件
const handleSectionVisible = (data: CallBackData) => {
	if (data.status === 'save') {
		data.done(true);
		sectionVisible.value = data.flag;
    if( isCreate ){
      window.location.href = `${location.origin}/#!/personalaccount`;
    } else {
      window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
    }
	} else {
    sectionVisible.value = data.flag;
  }
  
};


const handleClick = (type: boolean) => {
  // if (props.groupIndex < 0) {
  //   emits('update:groupIndex', 0)
  // }
  // if ( props.groupIndex > props.seriesGroupList.length - 1) {
  //   emits('update:groupIndex', props.seriesGroupList.length - 1)
  // }
  // const index = type ? props.groupIndex - 1 : props.groupIndex + 1;
  // emits('update:groupIndex', index);
  bus.emit("Header.changeGroupIndex", type ? -1 : 1);

};
</script>

<template>
  <div class="video-header">
    <div class="left">
      <i class="icon iconfont icon-fanhui"></i>
      <span class="back" @click="goback">返回</span>
      <span class="separator">｜</span>
      <span class="title">{{ props.title }}</span>
    </div>
    <div class="btn-group" v-if=" isView && route.query.viewType === 'all'">
      <a-button type="primary" class="prev-btn" :class="{'active': groupIndex === 0}" @click="() => {groupIndex != 0 && handleClick(true)}">上一个</a-button>
      <a-button type="primary" class="next-btn" :class="{'active': groupIndex === seriesGroupList.length - 1}" @click="() => {groupIndex != seriesGroupList.length - 1 && handleClick(false)}">下一个</a-button>
    </div>
    <a-button
      v-if=" isCreate || isEdit "
      class="submit"
      size="small"
      type="primary"
      @click="submit"
      :disabled="isView"
      >提交</a-button
    >

    <!-- 提交最终结果弹窗 -->
    <a-modal
      :visible="visible"
      :title="'提交'"
      :width="502"
      :mask-closable="false"
      :modal-class="'submit-dialog'"
      :footer="false"
      @cancel="handleCancel"
    >
      <div>
        <div class="sumbit-body">
          <div class="submit-title">确定提交该切片吗？</div>
          <div class="submit-tip">提交后切片将不再修改</div>
        </div>
        <div class="bottom-btn">
          <a-button
            type="primary"
            class="left-btn"
            @click="handleSubmitVisible({ status: 'more', flag: false })"
            >提交获取新切片</a-button
          >
          <a-button
            type="primary"
            class="right-btn"
            @click="handleSubmitVisible({ status: 'save', flag: false })"
            >提交并关闭</a-button
          >
        </div>
      </div>
    </a-modal>
		
  </div>
	<!-- 当前已经没有新切片的弹窗 -->
	<Dialog
		:visible="sectionVisible"
		:title="'提示'"
		:width="502"
		:maskClosable="false"
		:isForm="true"
		:hideCancel="true"
		:modalClass="'section-dialog'"
		:okText="'确认'"
		@update:visible="handleSectionVisible"
	>
		<template v-slot>
			<div>
				<div class="submit-title">
					<i class="iconfont icon-jingshi_" style="color: #ff7d00; font-size: 18px"></i>
					已没有新切片，请确认后退出该标注任务
				</div>
			</div>
		</template>
	</Dialog>
</template>

<style lang="less">
.video-header-modal {
  .arco-modal {
    width: 502px;
    height: 267px;
  }
  .arco-modal-header {
    background-color: #393a3c;
    border: none;
    height: 64px;
    .arco-modal-title {
      color: #fff;
      font-size: 18px;
    }
    .arco-icon-hover {
      color: #fff;
      font-size: 20px;
    }
  }
  .arco-modal-body {
    background-color: #272727;
    .title {
      color: #fff;
      font-size: 22px;
      text-align: center;
      padding-top: 8px;
    }
    .sub-title {
      color: #ccc;
      font-size: 14px;
      text-align: center;
      padding-top: 20px;
    }
  }
  .arco-modal-footer {
    background-color: #272727;
    border: none;
    padding-top: 23px;
    text-align: center;
    .arco-btn.arco-btn-secondary {
      background-color: #67c9d5;
      color: #fff;
    }
    .arco-btn.arco-btn-primary {
      background-color: #448e97;
      color: #fff;
    }
  }
}
.video-header {
  width: 100%;
  height: 54px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background: linear-gradient(
    180deg,
    rgba(12, 30, 33, 0.8) 3.6%,
    rgba(4, 29, 50, 0.8) 98.26%
  );
  .arco-btn.arco-btn-primary {
    background-color: #448e97;
    &:hover {
      background-color: #448e97;
    }
  }
  .left {
    .icon {
      font-size: 12px;
      margin-right: 5px;
      color: #fff;
      cursor: pointer;
    }
    .back {
      cursor: pointer;
    }
    .separator {
      margin: 0 5px 0 10px;
    }
    span {
      color: #fff;
    }
  }
  .submit {
    background-color: #448e97 !important;
    cursor: pointer;
    width: 92px;
    height: 32px;
    margin-right: 16px;
    &:hover {
      background-color: #448e97 !important;
    }
    &.arco-btn-disabled {
      background-color: #ccc !important;
      &:hover {
        background-color: #ccc !important;
      }
    }
  }
  .btn-group{
    margin-right: 16px;
    .arco-btn{
      width: 76px;
      height: 32px;
      border-radius: 2px;
      cursor: pointer;
    }
    .prev-btn{
      margin-right: 12px;
    }
    .active{
      background-color: rgba(68, 142, 151, 0.5);
      cursor: not-allowed;
    }
  }
}
.section-dialog.arco-modal,
.submit-dialog.arco-modal {
	background-color: #272727;
	.arco-modal-header {
    height: 64px;
    background-color: #393a3c;
    font-weight: 700;
    font-size: 18px;
    color: #fff;
    border: 0;
    .arco-modal-title,
    .arco-modal-close-btn {
      font-weight: 700;
      font-size: 18px;
      color: #fff;
    }
    .arco-icon-hover:hover::before {
      background-color: #616367;
    }
  }
	.arco-modal-body{
		text-align: center;
	}
	.submit-title {
		font-weight: 400;
		font-size: 22px;
		text-align: center;
		color: #fff;
		margin-bottom: 20px;
	}
	.submit-tip {
		font-weight: 400;
		font-size: 14px;
		text-align: center;
		color: #ccc;
	}
	.sumbit-body {
		margin-bottom: 32px;
	}
	.bottom-btn {
		.left-btn {
			margin-right: 18px;
		}
		button {
			width: 128px;
			height: 40px;
			background-color: #448e97;
			border-radius: 4px;
			font-weight: 400;
			font-size: 16px;
			color: #fff;
		}
		.arco-btn-primary:hover,
		.arco-btn-primary[type="button"]:hover {
			background-color: #67c9d5;
		}
	}
	.arco-modal-footer {
    text-align: center;
    border: 0;
    .arco-btn {
      width: 96px;
      height: 40px;
      font-weight: 400;
      font-size: 16px;
      border-radius: 4px;
    }
    .arco-btn-secondary {
      color: rgba(255, 255, 255, 0.7);
      background-color: #353535;
    }
    .arco-btn-primary {
      background-color: #448e97;
      border-color: #448e97;
    }
    .arco-btn-primary:hover,
    .arco-btn-primary[type="button"]:hover {
      background-color: #67c9d5;
      border-color: #67c9d5;
    }
  }
}
</style>
